package com.fadadianqi.logistics.admin.staff.service;

import com.fadadianqi.logistics.admin.staff.dao.MasterGroupDAO;
import com.fadadianqi.logistics.admin.staff.model.Group;
import com.fadadianqi.logistics.admin.staff.model.Master;
import com.fadadianqi.logistics.admin.staff.model.MasterGroup;
import com.fadadianqi.cache.Cache;
import com.fadadianqi.cache.CacheFactory;
import com.fadadianqi.commons.PrimaryKeyCreator;
import com.yeqiangwei.commons.util.ValidatorHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class MasterGroupService {

    private Cache cache = CacheFactory.getCache("staff");

    private static final String KEY_PREFIX = "groups_master_id_";

    public void masterToGroup(Master m, Group g) {
        MasterGroup mg = masterGroupDAO.getWithMasterIdAndGroupId(m.getId(), g.getId());
        if (mg == null) {
            mg = new MasterGroup();
            mg.setId(PrimaryKeyCreator.create());
            mg.setGroupId(g.getId());
            mg.setMasterId(m.getId());
            masterGroupDAO.create(mg);
            cache.del(KEY_PREFIX + m.getId());
        }
    }

    public void masterToAllGroup(Master m) {
        List<Group> gs = groupService.findAll();
        if (ValidatorHelper.isEmpty(gs)) {
            return;
        }
        for (Group g : gs) {
            masterToGroup(m, g);
        }
    }

    public List<Group> findGroupsByMaster(Master m) {
        if (m == null) {
            return null;
        }
        List<Group> gs = (List<Group>) cache.get(KEY_PREFIX + m.getId());
        if (ValidatorHelper.isNotEmpty(gs)) {
            return gs;
        }
        gs = new ArrayList<Group>();
        List<MasterGroup> mgs = masterGroupDAO.findByMasterId(m.getId());
        if (ValidatorHelper.isEmpty(mgs)) {
            return null;
        }
        for (MasterGroup mg : mgs) {
            Group g = groupService.getById(mg.getGroupId());
            if (g == null) {
                continue;
            }
            gs.add(g);
        }
        cache.set(KEY_PREFIX + m.getId(), gs);
        return gs;
    }

    public void delByMasterId(String masterId) {
        masterGroupDAO.delByMasterId(masterId);
    }

    @Autowired
    private GroupService groupService;

    @Autowired
    private MasterGroupDAO masterGroupDAO;

}
